/*
 * \brief  Test program for raising and handling region-manager faults
 * \author Norman Feske
 * \date   2008-09-24
 *
 * This program starts itself as child. When started, it first determines
 * wheather it is parent or child by requesting its own file from the ROM
 * service. Because the program blocks all session-creation calls for the
 * ROM service, each program instance can determine its parent or child
 * role by the checking the result of the session creation.
 */

/*
 * Copyright (C) 2008-2009 Norman Feske
 * Genode Labs, Feske & Helmuth Systementwicklung GbR
 *
 * This file is part of the Genode OS framework, which is distributed
 * under the terms of the GNU General Public License version 2.
 */

#include <base/printf.h>
#include <base/env.h>
#include <base/sleep.h>
#include <base/child.h>
#include <ram_session/connection.h>
#include <rom_session/connection.h>
#include <cpu_session/connection.h>
#include <cap_session/connection.h>
#include <rm_session/client.h>

using namespace Genode;


/***********
 ** Child **
 ***********/

enum { MANAGED_ADDR = 0x10000000 };


void read_at(addr_t addr)
{
	printf("perform read operation at 0x%p\n", (void *)addr);
	int value = *(int *)addr;
	printf("read value %x\n", value);
}

void modify(addr_t addr)
{
	printf("modify memory at 0x%p to %x\n", (void *)addr, ++(*(int *)addr));
}

void main_child()
{
	printf("child role started\n");

	/* perform illegal access */
	read_at(MANAGED_ADDR);

	while (true)
		modify(MANAGED_ADDR);

	printf("--- child role of region-manager fault test finished ---\n");
}


/************
 ** Parent **
 ************/

class Test_child : public Child
{
	public:

		/**
		 * Constructor
		 */
		Test_child(const char                     *name,
		           Genode::Dataspace_capability    elf_ds,
		           Genode::Ram_session_capability  ram,
		           Genode::Cpu_session_capability  cpu,
		           Genode::Cap_session            *cap)
		:
			Child(name, elf_ds, ram, cpu, cap, 0)
		{ }


		/**********************
		 ** Parent interface **
		 **********************/

		Genode::Session_capability session(const char *service_name, const char *args)
		{
			/* define session label for sessions forwarded to our parent */
			char buf[64];
			strncpy(buf, args, sizeof(buf));
			Arg_string::set_arg(buf, sizeof(buf), "label", "child");

			/* forward log-session request to our parent */
			if (!strcmp(service_name, "LOG"))
				return env()->parent()->session(service_name, buf);

			return Child::session(service_name, args);
		}
};


void main_parent(Dataspace_capability elf_ds)
{
	printf("parent role started\n");

	/* create environment for new child */
	static Ram_connection ram;
	static Cpu_connection cpu;
	static Cap_connection cap;

	/* transfer some of our own ram quota to the new child */
	enum { CHILD_QUOTA = 1*1024*1024 };
	ram.ref_account(env()->ram_session_cap());
	env()->ram_session()->transfer_quota(ram.cap(), CHILD_QUOTA);

	/* create child */
	static Test_child child("child", elf_ds, ram.cap(), cpu.cap(), &cap);

	static Signal_receiver fault_handler(&cap);

	/* configure child's rm session */
	static Rm_session_client rm(child.rm_session_cap());

	/* register fault handler */
	rm.fault_handler(fault_handler.cap(123));

	/* start execution of the new child */
	child.finalize_construction();

	/* allocate dataspace used for creating shared memory between parent and child */
	Dataspace_capability ds = env()->ram_session()->alloc(4096);
	volatile int *local_addr = (int *)env()->rm_session()->attach(ds);

	for (int i = 0; i < 4; i++) {

		printf("wait for region-manager fault\n");
		Signal fault = fault_handler.wait_for_signal();
		printf("received region-manager fault signal, request fault state\n");

		Rm_session::State state = rm.state();

		printf("rm session state is %s, pf_addr=0x%p\n",
		       state.type == Rm_session::READ_FAULT  ? "READ_FAULT"  :
		       state.type == Rm_session::WRITE_FAULT ? "WRITE_FAULT" :
		       state.type == Rm_session::EXEC_FAULT  ? "EXEC_FAULT"  : "READY",
		       state.addr);

		addr_t child_virt_addr = state.addr & ~(4096 - 1);

		/* allocate dataspace to resolve the fault */
		printf("attach dataspace to the child at 0x%p\n", child_virt_addr);
		*local_addr = 0x1234;

		rm.attach_at(ds, child_virt_addr);

		/* wait until our child modifies the dataspace content */
		while (*local_addr == 0x1234);

		printf("child modified dataspace content, new value is %x\n", *local_addr);

		printf("revoke dataspace from child\n");
		rm.detach((void *)child_virt_addr);
	}

	printf("--- parent role of region-manager fault test finished ---\n");
	sleep_forever();
}


/*************************
 ** Common main program **
 *************************/

int main(int argc, char **argv)
{
	printf("--- region-manager fault test ---\n");

	/* obtain own elf file from rom service */
	static Rom_connection rom("testrmfault");

	if (rom.cap().valid())
		main_parent(rom.dataspace());
	else
		main_child();

	return 0;
}
